import React, { useState } from "react";

// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'

import { incrementAction, decrementAction, incrementAsyncAction } from '../redux/actions/count'

// UI组件
function Count(props) {

    const {
        count,
        incrementAction,
        decrementAction,
        incrementAsyncAction,
        personCount
    } = props;

    const [optionValue, setOptionValue] = useState("1");

    const increment = () => {
        incrementAction(Number(optionValue));
    };

    const decrement = () => {
        decrementAction(Number(optionValue));
    };

    const incrementIfOdd = () => {
        if (optionValue % 2 !== 0)
            incrementAction(Number(optionValue));
    };

    const incrementAsync = () => {
        incrementAsyncAction(Number(optionValue), 1500);

    };

    return (
        <>
            <h1>我是Person组件,下方总人数{personCount}</h1>
            <h2>当前求和为：{count}</h2>
            <select value={optionValue} onChange={(e) => setOptionValue(e.target.value)}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>&nbsp;&nbsp;

            <button
                onClick={() => {
                    increment();
                }}
            >
                +
            </button>&nbsp;&nbsp;
            <button
                onClick={() => {
                    decrement();
                }}
            >
                -
            </button>&nbsp;&nbsp;
            <button
                onClick={() => {
                    incrementIfOdd();
                }}
            >
                当前求和为奇数再加
            </button>&nbsp;&nbsp;
            <button
                onClick={() => {
                    incrementAsync();
                }}
            >
                异步加
            </button>
        </>
    );
}

// 映射状态
const mapStateToProps = state => ({
    count: state.countReducer.count,
    personCount: state.personReducer.persons?.length || 0
})
// 使用connect()()创建并暴露一个Count的容器组件
export default connect(mapStateToProps,
    // mapDispatchToProps 映射操作状态的方法
    {
        incrementAction,
        decrementAction,
        incrementAsyncAction
    },
)(Count)
